/**
 * @Author: Liu, Yunfeng
 * @DateTime: 2021/4/7 23:16
 * @Description: 寻找两个正序数组的中位数
 */
public class findMedianSortedArrays {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int totalLength = nums1.length + nums2.length;
        int mid = 0;
        if (totalLength % 2 == 0) {
            mid = totalLength / 2 + 1;
        } else {
            mid= totalLength / 2 + 1;
        }
        int i = 0, j = 0;
        double value1 = 0, value2 = 0;
        while (mid > 0 && i < nums1.length && j < nums2.length) {
            value1 = value2;
            if (nums1[i] < nums2[j]) {
                value2 = nums1[i];
                i++;
            } else {
                value2 = nums2[j];
                j++;
            }
            mid--;
        }
        if (mid != 0) {
            while (mid > 0) {
                value1 = value2;
                if (i == nums1.length) {
                    value2 = nums2[j];
                    j++;
                } else {
                    value2 = nums1[i];
                    i++;
                }
                mid--;
            }
        }
        if(totalLength % 2 ==0){
            return (value1 + value2) / 2;
        }else{
            return value2;
        }

    }

    public static void main(String[] args) {
        int[] nums1 = {1, 2};
        int[] nums2 = {4};
        System.out.println(findMedianSortedArrays(nums1, nums2));
    }
}
